package cn.jason.user.service.impl;

import cn.jason.basic.Constants.BaseConstant;
import cn.jason.basic.dto.RegisterDto;
import cn.jason.basic.exception.BusinessException;
import cn.jason.basic.util.MD5Utils;
import cn.jason.basic.util.StrUtils;
import cn.jason.user.domain.Logininfo;
import cn.jason.user.domain.User;
import cn.jason.user.mapper.LogininfoMapper;
import cn.jason.user.mapper.UserMapper;
import cn.jason.user.service.IUserService;
import cn.jason.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jason
 * @since 2022-06-16
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void phoneRegister(RegisterDto dto) {
        String phone = dto.getPhone();
        String smsCode = dto.getSmsCode();
        String password = dto.getPassword();
        String passwordRepeat = dto.getPasswordRepeat();
        //空校验
       /* if(StringUtils.isEmpty(password)){
            throw new BusinessException("参数不能为空");
        }*/
        //密码和确认密码是否一致
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致");
        }
        //短信验证码判断
        String key = BaseConstant.RegisterConstants.REGISTER_SMS_PREFIX + phone;
        Object smsCodeTmp = redisTemplate.opsForValue().get(key);
        //验证码过期 重新获取
        if(smsCodeTmp == null){
            throw new BusinessException("验证码已过期,请重新获取");
        }
        //输入验证码 判断是否一致
        /*if(!smsCode.equalsIgnoreCase(smsCodeTmp.toString().split(":")[0])){
            throw new BusinessException("请输入正确验证码");
        }*/
        //保存数据 user表+logininfo
        User user = dto2User(dto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User dto2User(RegisterDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }
}
